package com.bigluo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Created by luojun on 2017/9/5.
 * spring容器bean获取策略
 */
public class CustomApplicationContextUtil implements ApplicationContextAware,DisposableBean {
    private Logger logger = LoggerFactory.getLogger(CustomApplicationContextUtil.class);
    private static ApplicationContext applicationContext;
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        logger.info("注入applicationContext对象到CustomApplicationContextUtil类中");
        this.applicationContext = applicationContext;
    }
    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T)applicationContext.getBean(name);
    }
    public static <T> T getBean(Class<T> requiredType) {
        assertContextInjected();
        return applicationContext.getBean(requiredType);
    }
    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }
    private static void assertContextInjected() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
        }
    }

    public void destroy() throws Exception {
        logger.debug("清除CustomApplicationContextUtil中的ApplicationContext:" + applicationContext);
        applicationContext = null;
    }
}
